package com.cn.fw4j.util.image;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class ImageHelper {
	public static String IMAGE_TYPE_GIF = "gif";
	public static String IMAGE_TYPE_JPG = "jpg";
	public static String IMAGE_TYPE_JPEG = "jpeg";
	public static String IMAGE_TYPE_BMP = "bmp";
	public static String IMAGE_TYPE_PNG = "png";
	public static String IMAGE_TYPE_PSD = "psd";
	
	public final static void scaleByHeight(String srcImagePath,String destImagePath,int destHeight){
		try{
			BufferedImage src = ImageIO.read(new File(srcImagePath));
			int width = src.getWidth();
			int height = src.getHeight();
			boolean flag = height > destHeight ? true : false; 
			double scale = 0.0;
			if(flag){
				scale = height / destHeight;
				width = (int)(width / scale);
				height = destHeight;
			}else{
				scale = destHeight / height;
				height = destHeight;
				width = (int)(width * scale);
			}
			Image image = src.getScaledInstance(width, height,Image.SCALE_DEFAULT);
			BufferedImage tag = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
			Graphics g = tag.getGraphics();
			g.drawImage(image,0,0,null);
			g.dispose();
			ImageIO.write(tag,"JPGE",new File(destImagePath));
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public final static void scaleByWidth(String srcImagePath,String destImagePath,int destWidth){
		try{
			BufferedImage src = ImageIO.read(new File(srcImagePath));
			int width = src.getWidth();
			int height = src.getHeight();
			boolean flag = width > destWidth ? true : false;
			double scale = 0.0;
			if(flag){
				scale = destWidth / width;
				width = destWidth;
				height = (int)(height * scale);
			}else{
				scale = width / destWidth;
				width = destWidth;
				height = (int)(height / scale);
			}
			Image image = src.getScaledInstance(width, height,Image.SCALE_DEFAULT);
			BufferedImage tag = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
			Graphics g = tag.getGraphics();
			g.drawImage(image,0,0,null);
			g.dispose();
			ImageIO.write(tag,"JPGE",new File(destImagePath));
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
